package com.ias.agdis_r.activity.task;

import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.mikephil.charting.charts.HorizontalBarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.adapter.QJMonitorAdapter;
import com.ias.agdis_r.bean.task.FLG10TaskBean;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.util.MyValueFormatter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2016/1/5.
 */
public class TaskBarChartActivity extends BaseActivity implements OnChartValueSelectedListener {

    private HorizontalBarChart mChart;
    private ActionBar actionBar;
    private List<List<FLG10TaskBean>> childList = new ArrayList<>();
    private List<String> groupList = new ArrayList<>();
    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_taskbarchart);
        initActionBar();
        mChart = (HorizontalBarChart) findViewById(R.id.chart1);
        mChart.setOnChartValueSelectedListener(this);
        // mChart.setHighlightEnabled(false);
        mChart.setScaleEnabled(false);
        mChart.setDoubleTapToZoomEnabled(false);
        mChart.setHighlightPerDragEnabled(false);
        mChart.setDrawBarShadow(false);
        mChart.setDrawValueAboveBar(true);
        mChart.setDescription("");
        // if more than 60 entries are displayed in the chart, no values will be drawn
        mChart.setMaxVisibleValueCount(60);
        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);
        // draw shadows for each bar that show the maximum value
        // mChart.setDrawBarShadow(true);
        // mChart.setDrawXLabels(false);
        mChart.setDrawGridBackground(false);
        // mChart.setDrawYLabels(false);
        XAxis xl = mChart.getXAxis();
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);
        xl.setDrawAxisLine(true);
        xl.setDrawGridLines(true);
        xl.setTextSize(12f);
        xl.setGridLineWidth(0.3f);

        MyValueFormatter formatter = new MyValueFormatter();

        YAxis yl = mChart.getAxisLeft();
        yl.setDrawAxisLine(true);
        yl.setDrawGridLines(true);
        yl.setTextSize(14f);
        yl.setGridLineWidth(0.3f);
        yl.setValueFormatter(formatter);
//        yl.setInverted(true);
        YAxis yr = mChart.getAxisRight();
        yr.setDrawAxisLine(true);
        yr.setDrawGridLines(false);
        yr.setTextSize(14f);
        yr.setValueFormatter(formatter);
//        yr.setInverted(true);

        mChart.animateY(2500);
        Legend l = mChart.getLegend();
        l.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT);
        l.setFormSize(8f);
        l.setXEntrySpace(4f);
        l.setEnabled(true);
        // mChart.setDrawLegend(false);
    }

    private void setValue() {
        getData();
        setData();
        mChart.notifyDataSetChanged();
        mChart.invalidate();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setValue();
    }

    private void getData() {
        groupList.clear();
        childList.clear();
        List<FLG10TaskBean> list = JavaBeanManager.getInstance().getFLG10Taskinfo().getList();
        if (null != list) {
            Map<String, List<FLG10TaskBean>> taskMap = new HashMap<String, List<FLG10TaskBean>>();
            for (FLG10TaskBean task : list) {
                if (!taskMap.containsKey(task.getTem())) {
                    taskMap.put(task.getTem(), new ArrayList<FLG10TaskBean>());
                }
                taskMap.get(task.getTem()).add(task);
            }
            groupList.addAll(taskMap.keySet());
            childList.addAll(taskMap.values());
        }
    }

    private void setData() {
        if (null == groupList || groupList.size() == 0 || null == childList
                || childList.size() == 0 || groupList.size() != childList.size()) {
            return;
        }
        ArrayList<String> xVals = new ArrayList<String>();
        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
        for (int i = 0; i < groupList.size(); i++) {
            xVals.add(groupList.get(i));
            yVals1.add(new BarEntry(getCount(i), i));
        }

        BarDataSet set1 = new BarDataSet(yVals1, getString(R.string.taskStateCount));
        set1.setColors(new int[]{Color.rgb(92, 185, 92), Color.rgb(90, 193, 233)});
        set1.setStackLabels(new String[]{getString(R.string.complete), getString(R.string.in_progress)});

        ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>();
        dataSets.add(set1);

        BarData data = new BarData(xVals, dataSets);
        data.setValueTextSize(16f);
        data.setValueFormatter(new MyValueFormatter());
        mChart.setData(data);
    }

    private float[] getCount(int i) {
        float[] count = new float[2];
        List<FLG10TaskBean> taskBeans = childList.get(i);
        int k = 0;
        for (int j = 0; j < taskBeans.size(); j++) {
            FLG10TaskBean taskBean = taskBeans.get(j);
            if (MessageModel.TCXX.equals(taskBean.getPid())
                    || MessageModel.TRJT.equals(taskBean.getPid())
                    || MessageModel.TEND.equals(taskBean.getPid())
                    || MessageModel.T_QJHS_YQ.equals(taskBean.getPid())
                    || MessageModel.TTRN.equals(taskBean.getPid())) {
                k++;
            }
        }
        count[0] = k;
        count[1] = taskBeans.size() - k;
        return count;
    }

    private void initActionBar() {
        actionBar = getActionBar();
        actionBar.setCustomView(LayoutInflater.from(TaskBarChartActivity.this).inflate(R.layout.actionbar_back_and_home, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        ImageView back = (ImageView) findViewById(R.id.action_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        ImageView home = (ImageView) findViewById(R.id.action_home);
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TaskBarChartActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
        TextView title = (TextView) findViewById(R.id.txt_title);
        title.setText(getString(R.string.barchart));
    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
        showPopupWindow(e);
    }

    private void showPopupWindow(Entry e) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(TaskBarChartActivity.this).inflate(
                R.layout.barchart_popupwindow, null);
        ListView listView = (ListView) contentView.findViewById(R.id.ListView);
        listView.setAdapter(new QJMonitorAdapter(TaskBarChartActivity.this, childList.get(e.getXIndex())));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (popupWindow != null)
                    popupWindow.dismiss();
            }
        });
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.color.gray2));
        popupWindow.showAtLocation(mChart, Gravity.CENTER, 0, 0);
    }

    @Override
    public void onNothingSelected() {

    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {

    }

    @Override
    protected void updateUI(String tag) {
        if (tag.equals(MessageModel.ITTL)) {
            setValue();
        }
    }
}
